package com.hxd.mall.utils.local

import android.app.Application
import android.util.Log
import com.hexin.locallibrary.network.OkHttpManager
import com.hxd.mall.constant.HxdConstants.Alias
import com.hxd.mall.constant.HxdConstants.Push_Id
import com.hxd.mall.constant.HxdConstants.isSaveAlias
import com.hxd.mall.constant.HxdConstantsNet
import com.hxd.mall.constant.HxdGlobalInfo.instance
import com.hxd.mall.network.service.ManagerFunctionApi
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.getBooleanData
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.saveBooleanData
import com.hxd.mall.utils.local.HxdSharePreferenceUtil.saveStringData
import com.hxd.threelibrary.BuildConfig
import com.hxd.threelibrary.getBugglyClient
import com.hxd.threelibrary.getJPushClient
import com.hxd.threelibrary.getUmClient
import com.meituan.android.walle.WalleChannelReader
import java.util.*

/**
 * 友盟极光同盾工具类
 */
object ThirdInitUtil {

    fun hostChange(host: String) {
        OkHttpManager.setUrl(host)
        HxdSharePreferenceUtil.saveStringData("domain", host)
        HxdConstantsNet.HOST_URL_ONLINE = host
        ManagerFunctionApi.reLoad()
    }

    val weixinAppId = "wx8339dc126d1d7388"
    val weixinAppSecret = "282e0cd6c06d71790f87e13831f5cc91"

    fun thirdInitUtils(application: Application) {
        //友盟
        getUmClient().init(
            application,
            "5db7db3d4ca35777dd000d33", "umeng",
            hasShare = true,
            weixinAppId = weixinAppId,
            weixinAppSecret = weixinAppSecret
        )

        //极光
        Push_Id = getJPushClient().init(application, BuildConfig.DEBUG).getRegistId(application)
        Log.d("reg_id", Push_Id)
        getJPushClient().checkPermission(application)

        //bugly，多渠道需求塞入
        val channel: String? = WalleChannelReader.getChannel(application)
        getBugglyClient().init(
            application,
            if (BuildConfig.DEBUG) "26c85aaab3" else "26c85aaab3",
            channel
        )
    }

    fun unBindJPush() {
        //解绑
        val toInt = Random(10000000000).nextInt()
        Log.d("unBindJPush", toInt.toString())
        getJPushClient().deleteAlias(instance, toInt)
        saveBooleanData(isSaveAlias, false)
    }

    fun bindJPush(alias: String?) {
        getJPushClient().checkPermission(instance)
        if (alias == null || alias.isNullOrEmpty())
            return

        //如果绑定成功了在取消此次绑定任务
        if (getBooleanData(isSaveAlias, false)) {
            return
        }
        unBindJPush()
        //重新绑定
        getJPushClient().setAlias(instance, alias) { state ->
            //如果之前是成功的则不处理，之前是失败的则更新状态
            if (state == 0 && !getBooleanData(isSaveAlias, false)) {
                saveBooleanData(isSaveAlias, true)
                saveStringData(Alias, alias)
            }
        }
    }
}